import * as api from "@/utils/request";
import { getToken, setToken } from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    user: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_USER(state, user) {
      state.user = user;
    }
  },

  actions: {
    /**
     * 登录
     * @param commit
     * @param userInfo 用户信息
     * @returns {Promise<unknown>}
     * @constructor
     */
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        api
          .request({
            url: "/api/user/login",
            data: userInfo,
            method: "post"
          })
          .then(({ data }) => {
            commit("SET_TOKEN", data.token);
            setToken(data.token);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};

export default user;
